package com.hengpeng.itfin.tools;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.codec.binary.Base64;

import com.hengpeng.common.util.FileHelper;
import com.hengpeng.common.util.MD5;

public class ReadFileGzipImpl implements ReadFile
{
	private String filepath;

	private String digest;

	private String source;

	public ReadFileGzipImpl(String filepath) throws Exception
	{
		this.filepath = filepath;
		gzip();
	}

	private void gzip() throws Exception
	{
		String fileData = FileHelper.readFileAsText(filepath, "GBK");
		digest = MD5.encodeString(fileData, "GBK");
		ByteArrayOutputStream o = new ByteArrayOutputStream();
		GZIPOutputStream gzout = new GZIPOutputStream(o);
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(gzout, "GBK"));
		out.write(fileData);
		out.flush();
		out.close();
		gzout.close(); // 返回压缩字节流
		byte[] data = o.toByteArray();
		o.close();
		source = new String(Base64.encodeBase64(data));
	}

	@Override
	public boolean verifyDigest()
	{
		return true;
	}

	@Override
	public String digest()
	{
		return digest;
	}

	@Override
	public String read()
	{
		return source;
	}

	public static void main(String[] args) throws Exception
	{
		String str = "E:\\DT306JG20140228.txt";
		ReadFileGzipImpl gzip = new ReadFileGzipImpl(str);
		System.out.println(gzip.read());

		ReadFileUnGzipImpl un = new ReadFileUnGzipImpl(gzip.read(), gzip.digest());
		System.out.println(un.read());
		System.out.println(un.verifyDigest());
	}
}
